#发送邮件
import smtplib,time
from email.mime.text import MIMEText
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from socket import gaierror, error
from common.config import *
from common.readfile import *
from common.logger import Log
from common.com import check_list


class Email():

    def mail(data):
        '''
        server:邮箱的smtp地址
        frommail：发送邮件的邮箱
        mailpass：邮箱授权码
        receivemain：接收邮件的邮箱
        '''
        log = Log()
        ymlpath = os.path.join(FILE_PATH, "config.yml")
        conf_run = Yaml(ymlpath)  # 打开Yaml文件
        conf_val = conf_run.data[0]  # 获取Yaml文件中的第一个字典的数据

        smtp_server= conf_val['smtp'] #邮箱的smtp地址
        from_mail = conf_val['from_mail'] #发送邮件的邮箱
        mail_pass = conf_val['mail_pass']#服务授权码
        to_mail = conf_val['to_mail'] #接收邮件的邮箱


        msg = MIMEMultipart() #MIMEMultipart：可发送多个附件
        msg["From"]=from_mail   #发件人
        msg["To"]=to_mail       #收件人
        # 邮件标题，中文进行转码
        msg["Subject"]=Header('自动化测试报告，请查收', 'utf-8').encode()

        '''
        文字部分
        '''
        TextPart = MIMEText(u"邮件发送测试")
        msg.attach(TextPart)
        '''
        附件分为：1.xlsx
                 2.jpg、png
                 3.pdf
                 4.mp3
                 5......
        '''
        data = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        check_list(REPORT_PATH) #校验目录是否存在
        report = REPORT_PATH +'\\%s.html' % data #文件路径
        #html类型附件
        XlsxPart = MIMEApplication(open(report,'rb').read())
        name = '%s.html' % data #附件名称
        XlsxPart.add_header('Content-Disposition', 'attachment', filename=name)
        msg.attach(XlsxPart)

        # # xlsx类型附件
        # XlsxPart = MIMEApplication(open(reportname, 'rb').read())
        # XlsxPart.add_header('Content-Disposition', 'attachment', filename="reportname.xlsx")
        # msg.attach(XlsxPart)
        #
        # # jpg类型附件
        # PicturePart = MIMEApplication(open(reportname, 'rb').read())
        # PicturePart.add_header('Content-Disposition', 'attachment', filename="reportname.jpg")
        # msg.attach(PicturePart)
        #
        # # pdf类型附件
        # PdfPart = MIMEApplication(open(reportname, 'rb').read())
        # PdfPart.add_header('Content-Disposition', 'attachment', filename="reportname.pdf")
        # msg.attach(PdfPart)
        #
        # # mp3类型附件
        # MP3Part = MIMEApplication(open(reportname, 'rb').read())
        # MP3Part.add_header('Content-Disposition', 'attachment', filename="reportname.mp3")
        # msg.attach(MP3Part)


        try:
            s = smtplib.SMTP_SSL(smtp_server, 465) #SSL：服务器+端口
        except (gaierror and error) as e:
            log.error('发送邮件失败,无法连接到SMTP服务器，检查网络以及SMTP服务器. %s', e)
        try:
            s.connect(smtp_server)  #连接
        except BaseException as msg:
            print(msg)
        try:
            s.login(from_mail, mail_pass) #登录邮箱
        except BaseException as msg:
            print(msg)
        try:
            # as_string()把MIMEText对象变成str
            s.sendmail(from_mail, to_mail, msg.as_string())
        except BaseException as msg:
            print(msg)
        try:
            s.quit()
            log.info(u'恭喜发送邮件成功！！！！！！')
        except smtplib.SMTPException as e:
            log.error ("Error: %s" % e)

if __name__ =='__main__':
    Email().mail()